package ru.papergames.battleserver.network.clientpackets.webserver;

import org.apache.log4j.Logger;
import ru.papergames.battleserver.model.AbstractPaperGameUser;
import ru.papergames.battleserver.model.PaperGameFlashUser;
import ru.papergames.battleserver.model.PaperGameNpcUser;
import ru.papergames.battleserver.model.UsersManager;
import ru.papergames.battleserver.model.battle.AbstractBattle;
import ru.papergames.battleserver.model.battle.BattleManager;
import ru.papergames.battleserver.network.serverpackets.flashuser.NotifyUserBattleCreateFailed;
import ru.papergames.battleserver.network.serverpackets.webserver.BattleCreateFailed;
import ru.papergames.battleserver.network.serverpackets.webserver.BattleCreated;

import java.util.ArrayList;
import java.util.List;

/**
 * @author atroshanin
 */
public class CreateNewBattle extends WebServerClientPacket{

    private static final Logger log = Logger.getLogger(CreateNewBattle.class.getName());

    private int battleOrderId;
    private int teamCount;
    private List<PaperGameFlashUser> pcUsers = new ArrayList<PaperGameFlashUser>();
    private List<PaperGameNpcUser> npcUsers = new ArrayList<PaperGameNpcUser>();
    private boolean readError = false;

    @Override
    protected void readImpl() {
        battleOrderId = readD();
        teamCount = readC();
        for (int teamNum = 0; teamNum < teamCount; teamNum++) {
            int teamSize = readC();
            for (int k = 0; k < teamSize; k++) {
                long playerId = readQ();
                AbstractPaperGameUser usr = UsersManager.getInstance().getPaperGameUser(playerId);
                if (usr != null && !usr.isDetached() && !usr.isInBattle()) {
                    if (usr instanceof PaperGameFlashUser) {
                        pcUsers.add((PaperGameFlashUser) usr);
                    } else {
                        npcUsers.add((PaperGameNpcUser) usr);
                    }
                    usr.setTeamId(teamNum);
                } else {
                    readError = true;
                }
            }
        }
    }

    @Override
    protected void runImpl() {
        if (!readError) {
            log.debug("creating new battle[" + battleOrderId + "]");
            AbstractBattle battle = BattleManager.getInstance().createNewBattle(getClient(), battleOrderId, teamCount, pcUsers, npcUsers);
            getClient().sendPacket(new BattleCreated(battle));
        } else {
            log.warn("Error creating battle(some pc player is detached or in another battle)");
            getClient().sendPacket(new BattleCreateFailed(battleOrderId));
            for (PaperGameFlashUser pcUser : pcUsers) {
                pcUser.sendPacket(new NotifyUserBattleCreateFailed(battleOrderId));
            }
        }
    }

    @Override
    public String getType() {
        return "[S] CreateNewBattle[" + CREATE_NEW_BATTLE_PACKET_ID + "]";
    }
}
